import React, { useState,useEffect} from 'react';
import { useHistory } from "react-router-dom";
import {Toast} from 'antd-mobile';

import Btn from "../../components/btn/Btn";
import Input from "../../components/input/Input";
import Txt from "../../components/txt/Txt";

import './user.less'
import no_user from '../../libs/img/user/no-user.png'
import UserList from './userList/UserList'
import http from '../../model/http'
import code from "../../model/code";

// import Vconsole from 'vconsole'
// const vConsole = new Vconsole()

function User() {
    const history = useHistory();
    const  query = http.useQuery();
    const  [type,setType] = useState(query.get('type')?query.get('type'):0);
    const  [name,setName] = useState('');
    const  [list,setList] = useState([]);
    const  [isBindOutUesr,setIsBindOutUesr] = useState(0);
    const [outUserId,setOutUserId] = useState('');
    const [ isSearch,setIsSearch] = useState(0);
    const [jurisdiction, setJurisdiction] = useState('') // 用户的权限
    const [hadRequest,setHadRequest] = useState(false)
    const [ entryIsHome,setEntryIsHome] = useState(0);  // 页面入口判断
    const getOutUser = async (outUserId)=>{
        const data = await http.post('/customer/checkCustomerBindoutUserId', {outUserId});
        console.log("获取外部联系人情况",data.data)
        // setList(data.data)
        // setIsBindOutUesr(data.isBind)
        if(data.isBind===1){
            history.push(`/user/details?isBind=${1}&outUserId=${outUserId}&entryIsHome=${entryIsHome}&showHeader=0`, data.data[0]); //跳转到客户详情页面
            return
        }else{
            setHadRequest(true)
        }

    }

    useEffect( async ()=>{


        window.localStorage.removeItem('tempSuqiu')
        window.localStorage.removeItem('phone')
        window.localStorage.removeItem('name')
        window.localStorage.removeItem('areaId')
        window.localStorage.removeItem('info')
        window.localStorage.removeItem('sex')
        window.localStorage.removeItem('age')
        window.localStorage.removeItem('show')

        window.localStorage.removeItem('stateId')
        window.localStorage.removeItem("lxId")
        window.localStorage.removeItem("unId")
        window.localStorage.removeItem('suqiumiaosu')
        window.localStorage.removeItem("fangansj")
        window.localStorage.removeItem("other")
        window.localStorage.removeItem("temp_customer_id")



        console.log('aaaaaaaaaaaa')
        await code.checkBind()
        const result =  await code.getContext()
        if(result=="single_chat_tools"||result=="contact_profile"){
            console.log("从聊天或者联系人详情进来的",result)
            const outUserId =await code.getOutUserId()
            setOutUserId(outUserId)
            console.log("外部联系id",outUserId)
            getOutUser(outUserId)
            // setHadRequest(true)
        }else{
            setHadRequest(true)
            setEntryIsHome(1)
        }
        setJurisdiction(sessionStorage.getItem('doctorJurisdiction')?JSON.parse(sessionStorage.getItem('doctorJurisdiction')):'')

    },[])


  const onSubmit = async () =>{
     let searchValue =name
     if(name.length<2){
         Toast.fail('搜索条件至少2位字符',1.5)
          return ;
     }
     setTimeout(async ()=>{
         const data = await http.post('/customer/searchCustomer',{
             params:searchValue,
             page:1,
             items:10
         });
         if( data.data.length>0){
             setList(data.data)
             setIsSearch(1)
         }else{
             Toast.fail('查无此人')
         }
     },50)

  }
  // 新增
  const add = ()=>{
    history.push("/user/edit?type=add&id=0");
  }

  // 新增客户
  const addCustomer =()=>{
    history.push("/user/newConsulation");
  }

  // 开单记录
  const billingHistory = () => {
    console.log('开单记录')
    history.push('/billing/history1')
  }
  return (
      <div>
          {
              hadRequest&&(
                  <div className='v-user g-pl20 g-pr20 '  >
                      <Input value={name}
                             onSubmit={onSubmit.bind(this)}
                             onChange={setName}
                             placeholder='姓名/手机号/卡号'/>

                      {list.length===0 ? (<>
                          <div className='v-center g-ta-c '>
                              <img src={no_user} style={{width:'2.96rem',height:'2.86rem'}} alt=""/>
                              <Txt className='g-mt30 g-f30'>提醒：未搜索到相关顾客信息，可直接新增</Txt>
                          </div>

                          <div className='g-abs g-b0 g-l0 g-w100'>
                              <Btn type='primary' onClick={onSubmit.bind(this)}>查找顾客</Btn>

                              {history.location.state!=undefined && history.location.state.gotoType == 'billing' && (
                                  <Btn type='warning' onClick={billingHistory}>开单记录</Btn>
                              )}

                               { (jurisdiction.authority == 7 || jurisdiction.authority == 9) ? (
                                  <Btn type='warning' onClick={addCustomer }>新增客户</Btn>
                              ):(
                                  <div></div>
                              ) }

                              {/* {type === '0' && (
                                  <Btn type='warning' onClick={add}>新增顾客</Btn>
                              )} */}
                              


                          </div>
                      </>):(
                          <div>
                              <UserList list={list}
                                        type={type}
                                        outUserId={outUserId}
                                        isBindOutUesr={isBindOutUesr}
                                        searchValue={name}
                                        isSearch={isSearch}
                                        parentFun={getOutUser.bind(this,outUserId)}
                                        entryIsHome={entryIsHome}
                              />
                          </div>
                      )}
                  </div>
              )

          }

      </div>

  )
}

export default User;